import React, {useEffect, useState} from 'react';
import {Form, Tree} from "antd";
import FormLayout from "@/assets/components/formLayout";
import {modulesUrl} from "@/assets/constant/modulesUrl";
import {ProFormText} from "@ant-design/pro-form";
import {useRequest} from "@@/plugin-request/request";
import {treeData} from "@/assets/service/baseService";
import {hooksSet} from "@/assets/utils/utils";
import {DownOutlined} from "@ant-design/icons";
import {menuIdListByRoleId} from "@/pages/sys/RoleList/service";

const RoleForm: React.FC<{}> = (props) => {

  // @ts-ignore
  const id = props.match.params.id;
  const [form] = Form.useForm();

  /**
   * 获取所有菜单
   */
  const [allMenuTree, setAllMenuTree] = useState([])
  const getAllMenuTreeRun = useRequest(() => treeData(modulesUrl.sysMenu), {
    manual: true,
    onSuccess: (result: any) => {
      hooksSet(setAllMenuTree, result);
    }
  }).run

  /**
   * 获取关联菜单id列表（去掉非叶子结点）
   */
  const [menuIdList, setMenuIdList] = useState<string[]>()
  const getMenuIdListRun = useRequest((id: string) => menuIdListByRoleId(id), {
    manual: true,
    onSuccess: (result) => {
      // 获取所有菜单
      getAllMenuTreeRun()
      // 数据插入all
      form.setFieldsValue({menuIdList: result.all})
      // 显示值需输入leaf，即叶子结点
      hooksSet(setMenuIdList, result.leaf);
    }
  }).run

  /**
   * 启动加载
   */
  useEffect(() => {
    // 获取关联菜单id列表
    getMenuIdListRun(id)
  }, []);

  return (
    <FormLayout
      id={id}
      title={"角色"}
      form={form}
      moduleUrl={modulesUrl.sysRole}
    >
      <ProFormText key="name" name="name" label="名称" placeholder="请输入名称"
                   rules={[{required: true, message: '名称为必填项',}]}/>
      <ProFormText key="enName" name="enName" label="英文名称" placeholder="请输入英文名称"
                   rules={[{required: true, message: '英文名称为必填项',}]} disabled={id === "0" ? false : true}/>
      <Form.Item key="menuIdList" name="menuIdList" label="菜单列表" initialValue={menuIdList} required>
        {
          allMenuTree && allMenuTree.length > 0 &&
          <Tree
            defaultExpandAll
            checkable
            defaultCheckedKeys={menuIdList}
            switcherIcon={<DownOutlined/>}
            treeData={allMenuTree}
            onCheck={(checkedKeys:any, e) => {
              let lastCheckedKeys:any = [];
              checkedKeys.forEach((checked:any)=>{
                if(checked.constructor === String){
                  lastCheckedKeys.push(checked)
                }
              })
              // e.halfCheckedKeys为半选状态，加上
              lastCheckedKeys = lastCheckedKeys.concat(e.halfCheckedKeys)
              form.setFieldsValue({menuIdList: lastCheckedKeys})
            }}
          />
        }
      </Form.Item>
    </FormLayout>
  );
};

export default RoleForm;
